package com.zxx.order.ui.activity

import android.annotation.SuppressLint
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.eightbitlab.rxbus.Bus
import com.eightbitlab.rxbus.registerInBus
import com.zqq.baselibrary.ext.onClick
import com.zqq.baselibrary.ext.setVisible
import com.zqq.baselibrary.ui.activity.BaseMvpActivity
import com.zqq.baselibrary.utils.YuanFenConverter
import com.zqq.provider.common.ProviderConstant
import com.zqq.provider.router.RouterPath
import com.zxx.order.R
import com.zxx.order.event.SelectAddressEvent
import com.zxx.order.injection.component.DaggerOrderComponent
import com.zxx.order.injection.module.OrderModule
import com.zxx.order.presenter.OrderConfirmPresenter
import com.zxx.order.presenter.iview.OrderConfirmView
import com.zxx.order.service.bean.Order
import com.zxx.order.ui.adapter.OrderGoodsAdapter
import kotlinx.android.synthetic.main.activity_order_confirm.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.jetbrains.anko.toast

/**
 * 订单确认页
 * wc
 */
@Route(path = RouterPath.OrderCenter.PATH_ORDER_CONFIRM)
class OrderConfirmActivity : BaseMvpActivity<OrderConfirmPresenter>(), OrderConfirmView {

    //注意要添加这个：ARouter.getInstance().inject(this)
    //跳转时传递的值:Kotlin中要添加JVM
    @Autowired(name = ProviderConstant.KEY_ORDER_ID)
    @JvmField
    var mOrderId: Int = 0

    private lateinit var mAdapter: OrderGoodsAdapter
    private var mCurrentOrder: Order? = null

    override fun injectComponent() {
        DaggerOrderComponent.builder()
                .activityComponent(mActivityComponent)
                .orderModule(OrderModule())
                .build()
                .inject(this)
        mPresenter.mView = this
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_order_confirm)
        //跳转时传递的值
        //mOrderId = intent.getIntExtra(ProviderConstant.KEY_ORDER_ID, -1)

        initView()
        initObserve()
        loadData()
    }

    //初始化视图
    private fun initView() {
        mShipView.onClick {
            ARouter.getInstance().build(RouterPath.OrderCenter.PATH_SHIP_ADDRESS)
                    .navigation()
        }
        mSelectShipTv.onClick {
            ARouter.getInstance().build(RouterPath.OrderCenter.PATH_SHIP_ADDRESS)
                    .navigation()
        }
        //提交订单按钮
        mSubmitOrderBtn.onClick {
            mCurrentOrder?.let {
                mPresenter.submitOrder(it)
            }
        }
        //订单中商品列表
        mOrderGoodsRv.layoutManager = LinearLayoutManager(this)
        mAdapter = OrderGoodsAdapter(this)
        mOrderGoodsRv.adapter = mAdapter
    }

    /**
     *初始化选择收货人事件监听
     */
    private fun initObserve() {
        Bus.observe<SelectAddressEvent>()
                .subscribe { t: SelectAddressEvent ->
                    run {
                        mCurrentOrder?.let {
                            it.shipAddress = t.address
                        }
                        updateAddressView()
                    }
                }.registerInBus(this)
    }

    //发送方： EventBus.getDefault().post(CartAllCheckedEvent(isAllChecked))
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun selectAddress(event: SelectAddressEvent) {
        mCurrentOrder?.let {
            it.shipAddress = event.address
        }
        updateAddressView()
    }

    /**
     * 加载订单数据
     */
    private fun loadData() {
        mPresenter.getOrderById(mOrderId)
    }


    /**
     * 根据是否有收货人信息，更新视图
     */
    @SuppressLint("SetTextI18n")
    private fun updateAddressView() {
        mCurrentOrder?.let {
            if (it.shipAddress == null) {
                mSelectShipTv.setVisible(true)
                mShipView.setVisible(false)
            } else {
                mSelectShipTv.setVisible(false)
                mShipView.setVisible(true)

                mShipNameTv.text = it.shipAddress!!.shipUserName + "  " +
                        it.shipAddress!!.shipUserMobile
                mShipAddressTv.text = it.shipAddress!!.shipAddress
            }
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        Bus.unregister(this)
        EventBus.getDefault().unregister(this)
    }

    //    -----------------接口实现------------
    //获取订单回调
    @SuppressLint("SetTextI18n")
    override fun onGetOrderByIdResult(result: Order) {
        mCurrentOrder = result
        mAdapter.setData(result.orderGoodsList)
        mTotalPriceTv.text = "合计：${YuanFenConverter.changeF2YWithUnit(result.totalPrice)}"

        updateAddressView()
    }

    //提交订单回调
    override fun onSubmitOrderResult(result: Boolean) {
        toast("订单提交成功")
        ARouter.getInstance().build(RouterPath.PaySDK.PATH_PAY)
                .withInt(ProviderConstant.KEY_ORDER_ID, mCurrentOrder!!.id)
                .withLong(ProviderConstant.KEY_ORDER_PRICE, mCurrentOrder!!.totalPrice)
                .navigation()

        finish()
    }

}
